﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Data;
using System.Web;

namespace ClickReadService
{
  public static class Utils
  {
    /// <summary>        
    /// 将对象序列化成json字符串(注：obj的类定义中要加正确的可序列化标志)        
    /// </summary>        
    /// <param name="obj"></param>        
    /// <returns></returns>        
    public static string ToJsonString(object obj)
    {
      string result = string.Empty; DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { jsonSerializer.WriteObject(ms, obj); result = Encoding.UTF8.GetString(ms.ToArray()); } return result;
    }

    /// <summary>        
    /// json字符串反序列为对象        
    /// </summary>        
    /// <param name="jsonString"></param>        
    /// <param name="objType"></param>        
    /// <returns></returns>        
    public static Object ToJsonObject(string jsonString, Type objType)
    {
      Object result = null; DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(objType); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { result = jsonSerializer.ReadObject(ms); } return result;
    }

    /// <summary>        
    /// 将DataTable序列化成json字符串        
    /// </summary>        
    /// <param name="dt"></param>        
    /// <returns></returns>        
    public static string ToJsonString(this DataTable dt)
    {
      StringBuilder JsonString = new StringBuilder();
      //Exception Handling                    
      if (dt != null && dt.Rows.Count > 0)
      {
        JsonString.Append("{ "); JsonString.Append("\"Rows\":[ "); for (int i = 0; i < dt.Rows.Count; i++)
        {
          JsonString.Append("{ ");
          for (int j = 0; j < dt.Columns.Count; j++)
          {
            if (j < dt.Columns.Count - 1)
            {
              JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString().Replace("\"", "\\\"") + "\":" + "\"" + dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\",");
            }
            else if (j == dt.Columns.Count - 1)
            {
              JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString().Replace("\"", "\\\"") + "\":" + "\"" + dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"");
            }
          }
          /**/
          /*end Of String*/
          if (i == dt.Rows.Count - 1)
          {
            JsonString.Append("} ");
          }
          else
          { JsonString.Append("}, "); }
        }
        JsonString.Append("]}"); return JsonString.ToString();
      }
      else
      { return null; }
    }
  }
}